package com.yanchi.controller;

import com.yanchi.service.Service1Api;
import com.yanchi.service.Service2Api;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@RestController
public class ConsumerController {

    // 负载均衡客户端
    @Autowired
    LoadBalancerClient loadBalancerClient;

    // 服务者名字
    private String serviceId = "nacos-provider";

    @GetMapping("service")
    public String service(){
        RestTemplate restTemplate = new RestTemplate();

        // 找到服务者，获取服务者的uri
        ServiceInstance choose = loadBalancerClient.choose(serviceId);
        URI uri = choose.getUri();

        // get请求访问服务者   http://127.0.0.1:56010(单服务下)
        String providerResult = restTemplate.getForObject(uri + "/service", String.class);

        return "consumer invoke | " + providerResult;

    }

    @org.apache.dubbo.config.annotation.Reference
    private Service2Api service2Api;

    @GetMapping("/service2")
    public String service2(){
        // 远程调用service2
        String providerResult = service2Api.dubboService2();
        return "consumer dubbo invoke | " + providerResult;

    }

    @org.apache.dubbo.config.annotation.Reference
    private Service1Api service1Api;

    @GetMapping("/service1")
    public String service1(){
        // 远程调用service1
        String providerResult = service1Api.dubboService1();
        return "consumer dubbo invoke | " + providerResult;
    }

    // 注入配置文件上下文
    @Autowired
    private ConfigurableApplicationContext applicationContext;

//    @Value("${common.name}")
//    private String commonName;

    @GetMapping("/config")
    public String getValue(){
        return applicationContext.getEnvironment().getProperty("common.name");
    }

}
